<?php

namespace app\admin\controller;

use app\api\controller\Myshoplazza;
use app\common\controller\Backend;
use ReflectionFunction;
use think\Db;
use think\Request;

/**
 * shoplaza导入订单管理
 *
 * @icon fa fa-circle-o
 */
class Feditionordershoplaza extends Backend
{
    
    /**
     * Feditionordershoplaza模型对象
     * @var \app\admin\model\Feditionordershoplaza
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Feditionordershoplaza;
        $this->view->assign("statusList", $this->model->getStatusList());

        $accounturl = $this->request->param('accounturl');
        $this->assignconfig('accounturl', $accounturl);
        $custom_status = $this->request->param('custom_status');
        $this->assignconfig('custom_status', $custom_status);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where2 = array();
            $accounturl = $this->request->param('accounturl');
            if(!empty($accounturl)){
                $where2['accounturl'] = $accounturl;
            }

            $where3 = array();
            $custom_status = $this->request->param('custom_status');
            if(!empty($custom_status)){
                if ($custom_status == 1) {
                    $where3['financial_status'] = 'paid';
                }elseif($custom_status == 2){
                    $where3['fulfillment_status'] = 'finished';
                }elseif($custom_status == 3){
                    $where3['order_status'] = 'cancelled';
                }
            }

            $list = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            if($lists){
                foreach ($lists as $k=>$v){
                    $accounturl = Db::name('fedition_accounturl')->where('id', '=', $v['accounturl'])->find();
                    if($accounturl){
                        $lists[$k]['accounturl_name'] = $accounturl['name'];
                        $lists[$k]['accounturl_url'] = $accounturl['url'];
                        $admin = Db::name('admin')->where('id', '=', $accounturl['admin_id'])->find();
                        if($admin){
                            $lists[$k]['admin_name'] = $admin['nickname'];
                        }else{
                            $lists[$k]['admin_name'] = '用户已删除';
                        }
                    }else{
                        $lists[$k]['accounturl_name'] = '店铺名称已删除';
                        $lists[$k]['admin_name'] = '用户已删除';
                    }

                    //运单号
                    $orderfulfillments = Db::name('fedition_orderfulfillmentsp')->where('order_id',$v['id'])->find();
                    if (!empty($orderfulfillments)) {
                        $lists[$k]['tracking_company'] = $orderfulfillments['tracking_company'];
                        $lists[$k]['tracking_number'] = $orderfulfillments['tracking_number'];
                    } else {
                        $lists[$k]['tracking_company'] = '';
                        $lists[$k]['tracking_number'] = '';
                    }
                    //部分商品
                    $orderquantityp = Db::name('fedition_orderquantityp')->where('order_id',$v['id'])->find();
                    if (!empty($orderquantityp)) {
                        $lists[$k]['quantityp_title'] = $orderquantityp['title'];
                    } else {
                        $lists[$k]['quantityp_title'] = '';
                    }
                }
            }
            $Statistics = array();
            $Statistics = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->field('sum(total_price) as zsum,sum(countnum) as countnum,sum(ytotal_price) as ytotalnum')
                ->find();
            $Statistics['zsum'] =  round($Statistics['zsum'],2); //10.46
            $Statistics['zcountnum'] =  $Statistics['countnum'];
            $Statistics['ytotalnum'] =  round($Statistics['ytotalnum'],2);
            $result = array("total" => $list->total(), "rows" => $lists, "Statistics" => $Statistics);
            return json($result);
        }
        return $this->view->fetch();
    }

    // 对象数值转普通数组
    public function test()
    {
        $callback = func_get_args()[0];
        $rf = new ReflectionFunction($callback);
        $params = array();
        foreach ($rf->getParameters() as $param) {
            $params[] = $param->getName();
        }
        var_dump($params);
    }

        /**
     * cancel_order
     */
    public function cancel_order()
    {
        $id = $this->request->param('ids');
        if(!empty($id)){
            $where['type'] = 1;
            $where['operation_id'] = $id;
            $logshoplaza = Db::name('fedition_logshoplaza')->where($where)->find();
            if (!empty($logshoplaza)) {
                $this->error('该订单已经取消');
            }
            $Myshoplazza = new Myshoplazza();
            $return = $Myshoplazza->cancel_order($id);
            if (!empty($return['error'])) {
                $this->error($return['error'],'',$return);
            }elseif(!empty($return['errors'][0]) && isset($return['errors'][0])){
                $this->error($return['errors'][0],'',$return);
            }else {
                $data['status'] = 'hidden';
                $this->ordershoplaza_log($id,1);
                Db::name('fedition_ordershoplaza')->where('id',$id)->update($data);
                $this->success('操作成功','',$return);
            }
        }else{
            $this->error('参数错误，请重新登录');
        }
    }

    /**
     * cancel_order
     */
    public function refund_order()
    {
        $id = $this->request->param('ids');
        if(!empty($id)){
            $where['type'] = 2;
            $where['operation_id'] = $id;
            $logshoplaza = Db::name('fedition_logshoplaza')->where($where)->find();
            if (!empty($logshoplaza)) {
                $this->error('该订单已经退款');
            }
            $Myshoplazza = new Myshoplazza();
            $return = $Myshoplazza->refund_order($id);
            if (!empty($return['error'])) {
                $this->error($return['error'],'',$return);
            }elseif(!empty($return['errors'][0]) && isset($return['errors'][0])){
                $this->error($return['errors'][0],'',$return);
            } else {
                $data['financial_status'] = 'refunded';
                $this->ordershoplaza_log($id,2);
                Db::name('fedition_ordershoplaza')->where('id',$id)->update($data);
                $this->success('操作成功','',$return);
            }
        }else{
            $this->error('参数错误，请重新登录');
        }
    }

    public function ordershoplaza_log($id,$type)
    {
        //$type 1取消订单 2订单退款
        $request = Request::instance();
        $data['title'] = '退款退单操作';
        $data['admin_id'] = $this->auth->id;
        $data['createtime'] = time();
        $data['ip'] = $request->ip();
        $data['type'] = $type;
        $data['operation_id'] = $id;
        Db::name('fedition_logshoplaza')->insert($data);
    }

    public function updateordertime()
    {
        $id = $this->request->param('ids');
        if(!empty($id)){
            //        更新每日汇总
            $Myshoplazza = new Myshoplazza();
            $return = $Myshoplazza->updateordertime($id);
            $this->success('更新成功','', $return);
        }else{
            $this->error('参数错误，请重新登录');
        }
    }

    /**
     * 新增采购成本
     */
    public function addmaterial()
    {
        $id = $this->request->param('ids');
        if(!empty($id)){
            //        更新每日汇总
            $Myshopify = new Myshoplazza();
            $return = $Myshopify->addmaterial($id);
            $this->success('更新成功','', $return);
        }else{
            $this->error('参数错误，请重新登录');
        }
    }

}
